package com.pedro.streamer.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.pedro.streamer.BmiBaseApp;
import com.pedro.streamer.R;
import com.pedro.streamer.adapter.AIRadioChooseAdapter;
import com.pedro.streamer.adapter.AIRadioListAdapter;
import com.pedro.streamer.manager.MediaPlayerClient;
import com.pedro.streamer.model.AudioItem;
import com.pedro.streamer.utils.RecyclerViewSpacesItemDecoration;
import com.pedro.streamer.utils.fileselector.SelectFileOrFolderDialog;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class AIRadioFragment extends Fragment implements AIRadioChooseAdapter.OnChooseClick {

    private static final String TAG = "AIRadioFragment";
    private RecyclerView recyclerView;
    private Context mContext;
    private AIRadioChooseAdapter radioChooseAdapter;
    private List<AudioItem> bgmItemList;
    private List<AudioItem> musicItemList;
    private CheckBox randomCheckBox;
    private CheckBox radioSupportCheckBox;
    private CheckBox radioBgmCheckBox;
    private SeekBar delayTimeBar;
    private SeekBar sup_volume_seek_bar;
    private SeekBar bgm_volume_seek_bar;

    private final static int BGM_CODE = 100;
    private final static int SUPPORT_CODE = 101;

    private FileFilter mFileFilter;

    private TextView seek_bar_max_title, bgm_volume_tv, sup_volume_tv;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContext = BmiBaseApp.getInstance().getApplicationContext();
        bgmItemList = new ArrayList<>();
        musicItemList = new ArrayList<>();


        recyclerView = view.findViewById(R.id.radio_list_recycler);
        randomCheckBox = view.findViewById(R.id.random_switch);
        radioSupportCheckBox = view.findViewById(R.id.radio_support);
        radioBgmCheckBox = view.findViewById(R.id.bgm_check_box);
        delayTimeBar = view.findViewById(R.id.seek_bar);
        sup_volume_seek_bar = view.findViewById(R.id.sup_volume_seek_bar);
        bgm_volume_seek_bar = view.findViewById(R.id.bgm_volume_seek_bar);
        seek_bar_max_title = view.findViewById(R.id.seek_bar_max_title);
        bgm_volume_tv = view.findViewById(R.id.bgm_volume_tv);
        sup_volume_tv = view.findViewById(R.id.sup_volume_tv);

        radioChooseAdapter = new AIRadioChooseAdapter(mContext);
        radioChooseAdapter.setOnChooseClick(this);
        radioChooseAdapter.getAiBgmListAdapter().setOnBgmItemClickListener(new AIRadioListAdapter.OnBgmItemClickListener() {
            @Override
            public void bgmItemClick() {
                radioBgmCheckBox.setChecked(true);
            }
        });

        HashMap<String, Integer> listHashMap = new HashMap<>();
        listHashMap.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION, 30);

        recyclerView.addItemDecoration(new RecyclerViewSpacesItemDecoration(listHashMap));


        GridLayoutManager listLayoutManager = new GridLayoutManager(mContext, 1);
        listLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(listLayoutManager);
        recyclerView.setAdapter(radioChooseAdapter);

        randomCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: 切换随机播放");
                radioChooseAdapter.getAiRadioSupportListAdapter().updateRandomState(randomCheckBox.isChecked() ? MediaPlayerClient.PlayMode.RandomPlay : MediaPlayerClient.PlayMode.ListPlay);
            }
        });

        radioSupportCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MediaPlayerClient.getInstance(mContext).getMusicList().size() == 0) {
                    Toast.makeText(getActivity(), "请先添加助播音乐", Toast.LENGTH_SHORT).show();
                    radioSupportCheckBox.setChecked(false);
                    return;
                }
                radioChooseAdapter.getAiRadioSupportListAdapter().playOrPause(radioSupportCheckBox.isChecked());
            }
        });

        radioBgmCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MediaPlayerClient.getInstance(mContext).getBmgList().size() == 0) {
                    Toast.makeText(getActivity(), "请先添加背景音乐", Toast.LENGTH_SHORT).show();
                    radioBgmCheckBox.setChecked(false);
                    return;
                }
                radioChooseAdapter.getAiBgmListAdapter().playOrPause(radioBgmCheckBox.isChecked());
            }
        });


        delayTimeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                seek_bar_max_title.setText(String.valueOf(seekBar.getProgress()));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

                Log.d(TAG, "onStopTrackingTouch: " + seekBar.getProgress());
                radioChooseAdapter.getAiRadioSupportListAdapter().updateDelayTime(seekBar.getProgress());
                seek_bar_max_title.setText(String.valueOf(seekBar.getProgress()));
            }
        });

        sup_volume_seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                radioChooseAdapter.getAiRadioSupportListAdapter().changeVolume(seekBar.getProgress()/100.00f);
                sup_volume_tv.setText(String.valueOf(seekBar.getProgress()));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                radioChooseAdapter.getAiRadioSupportListAdapter().changeVolume(seekBar.getProgress()/100.00f);
                sup_volume_tv.setText(String.valueOf(seekBar.getProgress()));
            }
        });

        bgm_volume_seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                radioChooseAdapter.getAiBgmListAdapter().changeVolume(seekBar.getProgress()/100.00f);
                bgm_volume_tv.setText(String.valueOf(seekBar.getProgress()));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                radioChooseAdapter.getAiBgmListAdapter().changeVolume(seekBar.getProgress()/100.00f);
                bgm_volume_tv.setText(String.valueOf(seekBar.getProgress()));
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        Log.d(TAG, "initData: " + MediaPlayerClient.getInstance(mContext).getSupVolume());
        randomCheckBox.setChecked(MediaPlayerClient.getInstance(mContext).getPlayMode() == MediaPlayerClient.PlayMode.RandomPlay);
        radioSupportCheckBox.setChecked(MediaPlayerClient.getInstance(mContext).isSupPlaying());
        radioBgmCheckBox.setChecked(MediaPlayerClient.getInstance(mContext).isBgmPlaying());
        delayTimeBar.setProgress((int) (MediaPlayerClient.getInstance(mContext).getDelayTime() / 1000));
        sup_volume_seek_bar.setProgress((int) (MediaPlayerClient.getInstance(mContext).getSupVolume() * 100));
        bgm_volume_seek_bar.setProgress((int) (MediaPlayerClient.getInstance(mContext).getBgmVolume() * 100));
        sup_volume_tv.setText(String.valueOf((int) (MediaPlayerClient.getInstance(mContext).getSupVolume() * 100)));
        bgm_volume_tv.setText(String.valueOf((int) (MediaPlayerClient.getInstance(mContext).getBgmVolume() * 100)));
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ai_radio, container, false);
    }

    @Override
    public void onClick(int requestCode) {
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setType("audio/mp3");
//        intent.setAction(Intent.ACTION_GET_CONTENT);
//        startActivityForResult(Intent.createChooser(intent, "Select Audio File"), requestCode);


        if (requestCode == 100) {
            new SelectFileOrFolderDialog(getActivity(), false, SelectFileOrFolderDialog.CHOICEMODE_ONLY_FILE, new SelectFileOrFolderDialog.OnSelectFileOrFolderListener() {
                @Override
                public void onSelectFileOrFolder(List<File> selectedFileList) {

                    bgmItemList.clear();
                    for (File file : selectedFileList) {
                        Log.d(TAG, "选中的文件: " + file.getAbsolutePath());
                        AudioItem item = new AudioItem();
                        item.setAudioName(file.getAbsolutePath().substring( file.getAbsolutePath().lastIndexOf("/") + 1));
                        item.setAudioFilePath(file.getAbsolutePath());
                        item.setPlaying(false);
                        bgmItemList.add(item);
                    }

                    if (bgmItemList.size() > 0) {
                        radioChooseAdapter.updateAudioList(bgmItemList, requestCode);
                    }
                }
            }).show();
        } else if (requestCode == 101) {
            new SelectFileOrFolderDialog(getActivity(), true, SelectFileOrFolderDialog.CHOICEMODE_ONLY_FOLDER, new SelectFileOrFolderDialog.OnSelectFileOrFolderListener() {
                @Override
                public void onSelectFileOrFolder(List<File> selectedFileList) {

                    musicItemList.clear();
                    File currentFile = selectedFileList.get(0);
                    mFileFilter = new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            if (pathname.getAbsolutePath().contains(".mp3")||pathname.getAbsolutePath().contains(".MP3")  || pathname.getAbsolutePath().contains(".ogg")) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    };

                    File[] files = currentFile.listFiles(mFileFilter);

                    for (File file : files) {
                        Log.d(TAG, "选中的文件夹中的file: " + file.getAbsolutePath());
                        AudioItem item = new AudioItem();
                        item.setAudioName(file.getAbsolutePath().substring( file.getAbsolutePath().lastIndexOf("/") + 1));
                        item.setAudioFilePath(file.getAbsolutePath());
                        item.setPlaying(false);
                        item.setFileName(currentFile.getName());
                        musicItemList.add(item);
                    }

                    if (musicItemList.size() > 0) {
                        radioChooseAdapter.updateAudioList(musicItemList, requestCode);
                    }

                }
            }).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
//        if (intent == null) {
//            return;
//        }
//        audioItemList.clear();
//        if (intent.getData() != null)    // 选择一个视频
//        {
//            Uri uri = intent.getData(); // 获得已选择视频的路径对象
//            Log.d(TAG, "onActivityResult: " + UrilToPath.getImageAbsolutePath(mContext,uri).substring( UrilToPath.getImageAbsolutePath(mContext,uri).lastIndexOf("/") + 1));
//            AudioItem item = new AudioItem();
//            item.setAudioName(UrilToPath.getImageAbsolutePath(mContext,uri).substring( UrilToPath.getImageAbsolutePath(mContext,uri).lastIndexOf("/") + 1));
//            item.setAudioFilePath(UrilToPath.getImageAbsolutePath(mContext,uri));
//            item.setPlaying(false);
//            audioItemList.add(item);
//        }
//        else if (intent.getClipData() != null)     // 选择多个视频
//        {
//            ClipData audios = intent.getClipData(); // 获取剪切板数据
//
//            if (audios.getItemCount() > 0)  // 至少选择了一个文件
//            {
//                for (int i = 0; i < audios.getItemCount(); i++) {
//                    Uri uri = audios.getItemAt(i).getUri();
//                    Log.d(TAG, "onActivityResult: " +  UrilToPath.getImageAbsolutePath(mContext,uri).substring( UrilToPath.getImageAbsolutePath(mContext,uri).lastIndexOf("/") + 1));
//                    AudioItem item = new AudioItem();
//                    item.setAudioName(UrilToPath.getImageAbsolutePath(mContext,uri).substring( UrilToPath.getImageAbsolutePath(mContext,uri).lastIndexOf("/") + 1));
//                    item.setAudioFilePath(UrilToPath.getImageAbsolutePath(mContext,uri));
//                    item.setPlaying(false);
//                    audioItemList.add(item);
//                }
//            }
//        }
//        if (audioItemList.size() > 0) {
//            radioChooseAdapter.updateAudioList(audioItemList, requestCode);
//        }
    }
}